package com.sqeakecleanblog.mediaplayer.components.ui
{
	import assets.ListItemDisplay;
	
	import caurina.transitions.*;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextFieldAutoSize;

	public class ListItem extends ListItemDisplay
	{
		private var _node:int;
		private var _hitarea:Sprite;
		private var _callback:Function;
		private var _isCurrentItem:Boolean;
		
		public function set isCurrent(value:Boolean):void
		{
			_isCurrentItem = value;
		}
		
		public function get node():int
		{
			return _node;
		}
		
		public function ListItem(text:String, node:int, clickCallback:Function)
		{
			label.autoSize = TextFieldAutoSize.LEFT;
			label.multiline = false;
			setText(text, node);
			_node = node;
			_callback = clickCallback;
			createBG();
			mouseChildren = false;
			enable();
			_isCurrentItem = false;
		}
		
		public function enable():void
		{
			buttonMode = true;
			addEventListener(MouseEvent.ROLL_OVER, onRollover);
			addEventListener(MouseEvent.ROLL_OUT, onRollout);
			addEventListener(MouseEvent.CLICK, onClick);
		}
		
		public function disable():void
		{
			buttonMode = false;
			removeEventListener(MouseEvent.ROLL_OVER, onRollover);
			removeEventListener(MouseEvent.ROLL_OUT, onRollout);
			removeEventListener(MouseEvent.CLICK, onClick);
		}
		
		public function startScroll():void
		{
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		public function endScroll():void
		{
			removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			Tweener.addTween(label, {x:prefix.width, time:0.5});
		}
		
		private function createBG():void
		{
			_hitarea = new Sprite();
			_hitarea.alpha = 0;
			addChildAt(_hitarea, 0);
			_hitarea.graphics.clear();
			_hitarea.graphics.beginFill(0xFFFFFF);
			_hitarea.graphics.drawRect(0,0,150,label.height);
			_hitarea.graphics.endFill();
		}
		
		private function setText(text:String, node:int):void
		{
			var prefixS:String = (node+1) < 10 ? "0"+(node+1) : (node+1).toString();
			label.text = text;
			prefix.text = prefixS + ": ";
		}
		
		private function onRollover(e:MouseEvent):void
		{
			Tweener.addTween(_hitarea, {alpha:1, time:0.4, transition:Equations.easeNone});
			label.textColor = prefix.textColor = 0x04002A;
			!_isCurrentItem && startScroll();
		}
		
		private function onRollout(e:MouseEvent):void
		{
			Tweener.addTween(_hitarea, {alpha:0, time:0.4, transition:Equations.easeNone});
			label.textColor = prefix.textColor = 0xFFFFFF;
			!_isCurrentItem && endScroll();
		}
		
		private function onClick(e:MouseEvent):void
		{
			_callback(e);
		}
		
		private function onEnterFrame(e:Event):void
		{
			label.x -= 2;
			if(label.x < -(label.width - prefix.width))
			{
				label.x = 150;
			}
		}
		
	}
}